package com.hellobike.hitch.business.main.view

import android.util.Log
import java.util.concurrent.ConcurrentLinkedQueue

/**
 * 类描述:多弹窗显示管理
 * 只需将HitchQueueDialog,Push进队列中即可
 * DialogManager.getInstance().pushToQueue(BuildBean)
 * created by chenqiuyue on 2019/1/7 11:11
 */
class DialogManager {
    private var mDialogBase: QueueDialog? = null

    companion object {
        private val TAG = "DialogManager"
        private val queue = ConcurrentLinkedQueue<QueueDialog>() //弹窗队列(线程安全)
        private var mInstance: DialogManager? = null
        fun getInstance(): DialogManager? {
            if (mInstance == null) {
                synchronized(DialogManager::class.java) {
                    if (mInstance == null) {
                        mInstance = DialogManager()
                    }
                }
            }
            return mInstance
        }
    }

    /**
     * 初始为0,pushToQueue 基数必然为1,所以小于2即可
     *
     * @return
     */
    fun canShow(): Boolean {
        return queue.size < 2/* && !isLock*/
    }


    /**
     * 每次弹窗调用PushQueue方法
     *
     * @param dialogBase
     */
    fun pushToQueue(dialogBase: QueueDialog?) {
        //添加到队列中
        if (dialogBase != null) {
            dialogBase?.setDissMissListener(object : QueueDialog.DialogDisMissListener {
                override fun onDissMiss() {
                    Log.e(TAG, "nextTask")
                    nextTask()
                }
            })
            Log.e(TAG, "add..")
            queue.add(dialogBase)
            //只有当前队列数量为1时才能进行下一步操作
            if (canShow()) {
                startNextIf()
            }
        }
    }


    /**
     * 显示下一个弹窗任务
     */
    private fun startNextIf() {
        if (queue != null && queue.isEmpty()) {
            return
        }
        //Todo 可在此处对弹窗进行排序
        oderDialog()
        mDialogBase = queue.element()
        if (mDialogBase != null) {
            mDialogBase?.show()
        } else {
            Log.e(TAG, "任务队列为空...")
        }
    }

    private fun oderDialog() {


    }


    /**
     * 清除对象
     */
    fun clear() {
        queue.clear()
        mDialogBase!!.dismiss()
        mDialogBase = null
    }

    /**
     * 移除队列的头,获取最新队列头
     */
    private fun removeTopTask() {
        queue.poll() //出栈
    }

    /**
     * 提供外部下一个任务的方法,在弹窗消失时候调用
     */
    private fun nextTask() {
        removeTopTask()
        startNextIf()
    }

}